package com.bytz.modules.cms.order.schedule;

import cn.hutool.core.bean.BeanUtil;
import com.bytz.common.system.vo.LoginUser;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.service.IAdminOrderService;
import com.bytz.modules.system.service.ISysUserService;
import com.bytz.modules.system.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class GenerateOpportunityJob implements Job {

    @Autowired
    private IAdminOrderService orderService;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        SysUserVo syscall = sysUserService.getUserByName("syscall");
        SecurityUtils.setLoginUser(BeanUtil.copyProperties(syscall, LoginUser.class));

        List<Order> orders = orderService.getNoProcessPrepaidOrders();

        // 需要自动创建opportunity的订单自动创建
        orders.forEach(order -> {
            try {
                orderService.createOpportunity(order);
            } catch (Exception e) {
                log.error("创建opportunity失败，order:" + order.getId(), e);
            }
        });

        SecurityUtils.setLoginUser(null);
    }
}
